package com.dstz.form.util.tableexcel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dstz.bus.api.model.IBusinessColumn;
import com.dstz.bus.api.model.IBusinessTable;
import com.dstz.form.util.tableexcel.column.BusinessColumnExcellor;
import com.dstz.form.util.tableexcel.column.BusinessColumnExcellorFactory;

/**
 * <pre>
 * 业务表转化excel者
 * </pre>
 * 
 * @author aschs
 * @date 2019年9月9日
 * @owner 大世同舟
 */
public class BusinessTableExcellor {
	private static Logger log = LoggerFactory.getLogger(BusinessTableExcellor.class);
	private IBusinessTable table;

	public BusinessTableExcellor(IBusinessTable table) {
		super();
		this.table = table;
	}

	/**
	 * <pre>
	 * 把从excel解析出来的数据，解析成ab表单能识别的数据
	 * </pre>
	 * 
	 * @param dataList
	 * @return
	 */
	public List<Map<String, Object>> fromExcel(List<Map<String, Object>> dataList) {
		log.debug("开始根据业务表【{}】解析excel内容：", table.getComment());
		log.debug("解析前：\n" + dataList.toString());
		List<Map<String, Object>> list = new ArrayList<>();
		dataList.forEach(data -> {
			Map<String, Object> map = new HashMap<>();
			data.forEach((key, val) -> {
				IBusinessColumn column = getColumnByComment(key);
				if (column == null) {
					return;
				}
				BusinessColumnExcellor excellor = BusinessColumnExcellorFactory.get(column);
				Object value = val;
				if (excellor != null) {
					value = excellor.fromExcel(column, val);
				}
				map.put(column.getKey(), value);
			});
			list.add(map);
		});
		log.debug("解析后：\n" + list);
		return list;
	}

	/**
	 * <pre>
	 * 把ab表单的数据转化成excel的数据
	 * </pre>
	 * 
	 * @param dataList
	 * @return
	 */
	public List<Map<String, Object>> toExcel(JSONArray dataList) {
		log.debug("开始根据业务表【{}】转化excel内容：", table.getComment());
		log.debug("转化前：\n" + dataList.toString());
		List<Map<String, Object>> list = new ArrayList<>();
		for (int i = 0; i < dataList.size(); i++) {
			JSONObject data = dataList.getJSONObject(i);
			Map<String, Object> map = new HashMap<>();
			data.forEach((key, val) -> {
				IBusinessColumn column = table.getColumnByKey(key);
				BusinessColumnExcellor excellor = BusinessColumnExcellorFactory.get(column);
				Object value = val;
				if (excellor != null) {
					value = excellor.toExcel(column, val);
				}
				map.put(column.getKey(), value);
			});
			list.add(map);
		}
		log.debug("转化后：\n" + list);
		return list;
	}

	/**
	 * <pre>
	 * 根据字段描述获取字段
	 * </pre>
	 * 
	 * @param comment
	 * @return
	 */
	private IBusinessColumn getColumnByComment(String comment) {
		for (IBusinessColumn c : table.getColumns()) {
			if (comment.equals(c.getComment())) {
				return c;
			}
		}
		return null;
	}

}
